import 'package:dio/dio.dart';
import 'bd_http_config.dart';

class HttpRequest {
  static final BaseOptions baseOptions = BaseOptions(
      baseUrl: HttpConfig.baseUrl, connectTimeout: HttpConfig.timeOut,headers: {"appVersion":"1.2.0","cookie":"cookie"});

  //    创建dio对象 每次网络请求都会调用dio，所以没有必要每次都去创建一个dio对象，因此在此处创建一个static的dio对象，减少内存
  static final Dio dio = Dio(baseOptions);

  static Future<T> request<T>(String url,
      {String method = "get", Map<String, dynamic> params,Interceptor interceptor}) async {
//1.创建一个个性化配置
    final option = Options(method: method);
//    创建全局默认拦截器
    Interceptor defaultInterceptor = InterceptorsWrapper(
      onError: (err){
        print("错误拦截");
        return err;
      },
      onRequest: (request){
        print("请求拦截");
      return request;
      },
      onResponse: (response){

        print("响应拦截");
        return response;
      }
    );
    List <Interceptor> inters = [defaultInterceptor];
    if(interceptor != null){
      inters.add(interceptor);
    }
    dio.interceptors.addAll(inters);
//  2.发送网络请求
    try {
      Response response =
      await dio.request(url, queryParameters: params, options: option);
      return response.data;
    } on DioError catch (error) {
      return Future.error(error);
    }
//    Response response =
//    await dio.request(url, queryParameters: params, options: option);
//    return response.data;
  }
}
